package com.apache.gateway.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.alibaba.fastjson.JSONObject;
import com.apache.tools.OsUtils;

/**
 * @description: 转换日志为logstash格式报文
 * @author: Hou Dayu
 * @date: Created in 2020/4/7
 */
public class JsonLogConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        JSONObject object = new JSONObject();
        String msg = iLoggingEvent.getFormattedMessage().trim();//.getMessage();
        try {
            object.put("ipAddress", OsUtils.getLocalIp());
            if(msg.startsWith("traceId = ") || msg.startsWith("processingStage = ") || msg.startsWith("exception = ")){
                String str[] = msg.split(";");
                for(int i= 0;i<str.length;i++){
                    String vals[] = str[i].split(" = ");
                    if(vals.length>1) {
                        object.put(vals[0].trim(), vals[1]);
                    }else{
                        object.put(vals[0].trim(), "");
                    }
                }
                object.put("message",msg.replaceAll("\n","").replaceAll("\r","").replaceAll(";","；"));
                if(!object.containsKey("level")) {
                    object.put("level", iLoggingEvent.getLevel().levelStr);
                }
            } else {
                object.put("message",msg.replaceAll("\n","").replaceAll("\r","").replaceAll(";","；"));
                object.put("level", Level.INFO.levelStr);
            }
            return object.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
